import db, { Doc } from '../utils/db'

interface dbScope {
  type: 'plugin'
  name: string
}

class DB {
  _db?: db
  init(dbPath: string) {
    this._db = new db(dbPath)
    this._db.init()
  }

  private calId(id: string, scope?: dbScope) {
    return `${scope?.type ?? ''}:${scope?.name ?? ''}:${id}`
  }

  async get<T>(id: string, scope?: dbScope) {
    const ret = await this._db?.get<T>(this.calId(id, scope))

    if (ret?._id) {
      ret._id = ret._id.split(':')[2]
    }
    return ret
  }

  async put<T>(doc: Doc<T>, scope?: dbScope) {
    doc._id = this.calId(doc._id, scope)
    const ret = await this._db?.put<T>(doc)
    if (ret?.id) {
      ret.id = ret.id.split(':')[2]
    }
    return ret
  }

  async remove<T>(id: string | Doc<T>, scope?: dbScope) {
    if (typeof id === 'string') {
      id = this.calId(id, scope)
    } else {
      id._id = this.calId(id._id, scope)
    }

    const ret = await this._db?.remove(id)
    if (ret?.id) {
      ret.id = ret.id.split(':')[2]
    }
    return ret
  }
}

export default new DB()
